package com.practice.concurrency;

import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class ScheduledExecutorMain {

	public static void main(String[] args) {
		final ScheduledExecutorService scheduler = Executors
				.newScheduledThreadPool(2);
		final ScheduledFuture<?> beeperHandler0 = scheduler
				.scheduleAtFixedRate(new Beeper("Fixed Rate"), 1, 3, TimeUnit.SECONDS);
		final ScheduledFuture<?> beeperHandler1 = scheduler
				.scheduleWithFixedDelay(new Beeper("Fixed Delay"), 2, 3, TimeUnit.SECONDS);
		scheduler.schedule(new Runnable() {
			@Override
			public void run() {
				beeperHandler0.cancel(true);
				beeperHandler1.cancel(true);
				scheduler.shutdown();
			}
		}, 30, TimeUnit.SECONDS);
	}
}

class Beeper implements Runnable {
	private String id;

	public Beeper(String id) {
		this.id = id;
	}
	
	@Override
	public void run() {
		System.out.println(new Date() + " [" + id + "] beep");
		try {
			Thread.sleep(1000);
		} catch (InterruptedException ex) {
			ex.printStackTrace();
		}
	}
}